layui.use(['form', 'layer', 'jquery'], function(){
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.jquery;

    // 支付方式选择效果
    $('.pay-method-card').click(function(){
        $('.pay-method-card').removeClass('selected');
        $(this).addClass('selected');
        $(this).find('input[type="radio"]').prop('checked', true);
        form.render('radio');
    });

    // 金额输入限制
    $('input[name="amount"]').on('input', function(){
        this.value = this.value.replace(/[^\d.]/g, '');
        if(this.value.split('.').length > 2) 
            this.value = this.value.replace(/\.+$/g, '');
    });

    // 表单提交
    form.on('submit(submitPayTest)', function(data){
        layer.load(2);
        $.ajax({
            url: './ajax/pay_cs',
            type: 'POST',
            data: data.field,
            dataType: 'json',
            success: function(res){
                layer.closeAll('loading');
                if(res.code === 200){
                    layer.msg(res.msg, {
                        icon: 1,
                        time: 2000,
                        shade: 0.4
                    }, function(){
                        window.location.href = res.pay_url;
                    });
                } else {
                    layer.msg(res.msg || '充值失败，请重试', {
                        icon: 2,
                        time: 2000,
                        shade: 0.4
                    });
                }
            },
            error: function(xhr, status, error){
                layer.closeAll('loading');
                layer.msg('服务器错误！', {
                    icon: 2,
                    time: 2000,
                    shade: 0.4
                });
            }
        });

        return false;
    });
});